package zrar.panel;

import java.awt.CardLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import zrar.BaseSetFrame;
import zrar.entity.AnswerPeople;
import zrar.entity.Prize;
import zrar.util.ExcelUtil;
import zrar.util.SystemUtil;
import zrar.util.ToolUtil;


public class MainPanel extends JPanel implements Observer{

	private static List<AnswerPeople> peoples = new ArrayList<AnswerPeople>();
	private static List<Prize> prizes = new ArrayList<Prize>();
	private Prize prize;
	
	private static final long serialVersionUID = 1L;
		
	private BaseSetFrame baseSetFrame;
	private Image backImage;
	
	private CardLayout cardLayout;
	
	private MenuPanel menuPn;
	private JPanel menuPanel;
	private SwitchPanel switchPanel;	
	private JPanel buttonPanel;
	private ButtonPanel butPn;
	//private JPanel tipPanel;
	//private JLabel tip_lb;
		
	private DisplayPanel displayPanel;  //抽奖面板
	private ResultPanel resPn; //结果面板
	private JPanel resultPanel;
	
	private int position_x=20;
	private int position_y=20;
	
	private static final int READY=0;
	private static final int RUN=1;
	private static final int STOP=2;
	private static final int SHOW=3;
	private static final int OPEN=4;
	private static final int CHANGE=5;
	private static final int Refresh=6;
	
	public MainPanel() {
		this.setLayout(null);
		menuPn = new MenuPanel();
		menuPn.addObserver(this);
		menuPanel = menuPn.getPane();
		
		
		switchPanel = new SwitchPanel();
		
		butPn = new ButtonPanel();
		butPn.addObserver(this);
		buttonPanel  = butPn.getPane();
		
		cardLayout = new CardLayout();
		switchPanel.setLayout(cardLayout);
		
		displayPanel = new DisplayPanel();
		
		resPn = new ResultPanel();
		resPn.addObserver(this);
		resultPanel = resPn.getPane();
		
		
		switchPanel.add(displayPanel,"disP");
		switchPanel.add(resultPanel,"resP");
		
		
		init();
		
		this.add(menuPanel);
		this.add(switchPanel);
		this.add(buttonPanel);
	}

	private void init() {
		String img=SystemUtil.backgroud_image;
		if(img==null||img.trim().isEmpty()){
			backImage = SystemUtil.createImageIcon("bg_red.jpg").getImage();
		}else{
			backImage = new ImageIcon(img).getImage();
		}
		
		menuPanel.setBounds(position_x+10,position_y-13,100,130);		
		switchPanel.setBounds(position_x+130,position_y+170,715,476);		
		buttonPanel.setBounds(position_x+130,position_y+670,700,55);		
		buttonPanel.setOpaque(false);
		
	}
	

	@Override
	public void update(Observable o, Object arg) {
		int ActionNum=((ActionTouchImpl) o).getActionNum();
		
		if(ActionNum==READY){
			ready_Action();
		}else if(ActionNum==SHOW){
			show_Action();
		}else if(ActionNum==OPEN){
			open_Action();
		}else if(ActionNum==CHANGE){
			change_Action();
		}else if(ActionNum==Refresh){
			
			refreshViewForResultPanel();
		}
	}

	public void ready_Action() {
		resPn.stopScroll();
		cardLayout.show(switchPanel, "disP");
		menuPn.closeMenuPanel();//隐藏 设置菜单		
		
		//1、检验数据导入，奖项设置
		peoples=SystemUtil.getPeoplelist();
		prizes=SystemUtil.getPrizelist();
		if(peoples.size()<=0){
			JOptionPane.showMessageDialog(null, "候选人名单为空,请先导入名单");
			return ;
		}
		if(prizes.size()<=0){
			JOptionPane.showMessageDialog(null, "奖项为空,请先设置好奖项");
			return ;
		}
		
		//Readystatu is true,
		if(SystemUtil.getReadystatu()||displayPanel.isRunning()){
			return ;
		}
		
		//2、屏幕正中间提示信息
		int finishPrizeNum = 0;
		for(Prize prize : prizes){
			if(prize.getIsFinish() || prize.getPersons().size()==prize.getTotal()){				
				finishPrizeNum++;
			}else{
				SystemUtil.setCurPrize(prize);
				break;
			}
		}
		
		//提示 面板显示 空白
		displayPanel.showInTisPanel(" ");
		
		if(finishPrizeNum==prizes.size()){			
			ShowInRunPanel("所有的奖项已经抽完");
			//JOptionPane.showMessageDialog(null, "所有的奖项已经抽完");
			//给用户显示抽奖结果
			//show_Action();
			return ;
		}	
		
		Prize nowPriz = SystemUtil.getCurPrize();
		String prizeInfo = getNowPrizeInfo(nowPriz);
		ShowInRunPanel(prizeInfo);
		
		
		//3、按钮 变灰色
		butPn.changeReadyBtn(0);
		
		
		//4、改变ready状态
		SystemUtil.setReadystatu(true);	
	}
	

	public void run_Action() {
		resPn.stopScroll();
		cardLayout.show(switchPanel, "disP");
		menuPn.closeMenuPanel();//隐藏 设置菜单
		
		if(!SystemUtil.getReadystatu()){
			JOptionPane.showMessageDialog(null, "请先按下准备按钮");
			return ;
		}
		
		//检查奖项 是否 抽完
		int finishPrizeNum = 0;	
		//本次 真正要抽的人数
		int viewNum = 0;
		for(Prize prize : prizes){
			if(prize.getIsFinish() || prize.getPersons().size()==prize.getTotal()){				
				finishPrizeNum++;
			}else{									
				SystemUtil.setCurPrize(prize);
				int temp =prize.getTotal()-prize.getPersons().size();
				if(temp>=prize.getFetchnum()){
					SystemUtil.setViewLabelNum(prize.getFetchnum());
					viewNum = prize.getFetchnum();
				}else{
					SystemUtil.setViewLabelNum(temp);
					viewNum = temp;
				}
				break;
			}
		}
		
		
		if(finishPrizeNum==prizes.size()){
			JOptionPane.showMessageDialog(null, "所有的奖项已经抽完");
			ShowInRunPanel("所有的奖项已经抽完");			
			//给用户显示抽奖结果
			show_Action();			
			return ;
		}			
						
		//各个奖项 每一次抽的人数不一样, 决定着 DisplayPanel中JLabel数量 是否要重绘制
		prize = SystemUtil.getCurPrize();
		if(viewNum==SystemUtil.getTotalLabelNum()){
			//一样的话就 不管了
		}else {
			RepaintLabelsInDisplayPanel(viewNum);
		}
		
		//提示当前抽的奖项 信息
		Prize nowPriz = SystemUtil.getCurPrize();
		String prizeInfo = getNowPrizeInfo(nowPriz);
		displayPanel.showInTisPanel(prizeInfo);
		
		
		if(viewNum>peoples.size()){
			JOptionPane.showMessageDialog(null, "亲!! 候选人数不够了.  本次要抽奖的人数:"+viewNum+",候选人数："+peoples.size());
			return ;
		}
		
		SystemUtil.setResultSave(false);//退出程序时，提示数据是否保存的作用
		if(!displayPanel.isRunning()){
			displayPanel.start();
		}		
	}
	
	// 重绘 DisplayPanel中JLabel的数量
	private void RepaintLabelsInDisplayPanel(int viewNum) {				
		refreshView();
		
		//去掉原来的 Component
		displayPanel.removeAllinRunPanel();
		
		//DisplayPanel的布局
		Font font = null;
				
		if(viewNum<=5){
			displayPanel.setLayoutInRun(new GridLayout(viewNum,2));
			font = new Font("宋体",Font.BOLD,45);
		}else if (viewNum<=10){
			int grid =(int) Math.ceil((double)viewNum/2);
			displayPanel.setLayoutInRun(new GridLayout(grid,2));
			font = new Font("宋体",Font.BOLD,32);
		}else if (viewNum<=24){
			displayPanel.setLayoutInRun(new GridLayout(8,3));
			font = new Font("宋体",Font.BOLD,20);
		}else if (viewNum<=27){
			displayPanel.setLayoutInRun(new GridLayout(9,3));
			font = new Font("宋体",Font.BOLD,18);
		}else if (viewNum<=40){
			displayPanel.setLayoutInRun(new GridLayout(10,4));
			font = new Font("宋体",Font.BOLD,16);
		}else if (viewNum<=50){
			displayPanel.setLayoutInRun(new GridLayout(10,5));
			font = new Font("宋体",Font.BOLD,14);
		}else if(viewNum<=60){
			displayPanel.setLayoutInRun(new GridLayout(12,5));
			font = new Font("宋体",Font.BOLD,13);
		}else if(viewNum<=70){
			displayPanel.setLayoutInRun(new GridLayout(14,5));
			font = new Font("宋体",Font.BOLD,12);
		}else if(viewNum<=80){
			displayPanel.setLayoutInRun(new GridLayout(16,5));
			font = new Font("宋体",Font.BOLD,12);
		}else{
			displayPanel.setLayoutInRun(new GridLayout(18,5));
			font = new Font("宋体",Font.BOLD,12);
		}
		
		
		//JLabel 的个数		
		for(int i=0;i<viewNum;i++){
			JLabel lab = new JLabel("",JLabel.CENTER);
			lab.setFont(font);
			displayPanel.addInRun(lab);
		}
		
		//设置好了之后,别忘了
		SystemUtil.setTotalLabelNum(viewNum);
	}
	
	private void ShowInRunPanel(String info) {	
		refreshView();
		displayPanel.removeAllinRunPanel();
		
		Font font = new Font("宋体",Font.BOLD,36);
		
		if(info.length()>15){
			String split[]=ToolUtil.splitInfo(info);
			
			displayPanel.setLayoutInRun(new GridLayout(4,2));
			JLabel lab_h = new JLabel(" ",JLabel.CENTER);	
			JLabel lab0 = new JLabel(split[0],JLabel.CENTER);			
			lab0.setFont(font);
			JLabel lab1 = new JLabel(split[1],JLabel.CENTER);			
			lab1.setFont(font);
			JLabel lab_t = new JLabel(" ",JLabel.CENTER);
			displayPanel.addInRun(lab_h);
			displayPanel.addInRun(lab0);
			displayPanel.addInRun(lab1);
			displayPanel.addInRun(lab_t);
		}else{
			displayPanel.setLayoutInRun(new GridLayout(1,2));
			JLabel lab = new JLabel(info,JLabel.CENTER);
			lab.setFont(font);
			displayPanel.addInRun(lab);
		}		
		SystemUtil.setTotalLabelNum(0);
	}
	
	private String getNowPrizeInfo(Prize nowPriz){
		String pname = nowPriz.getPname();
		int total = nowPriz.getTotal();
		int size = nowPriz.getPersons().size();
		int fetchNum= nowPriz.getFetchnum();
		String tipInfo=" ";
		if(total==fetchNum){
			tipInfo = "现抽取"+pname+"(共"+total+"名)";
		}else{
			int times =(int) Math.ceil((double)total/fetchNum);
			fetchNum = ToolUtil.getRealFetchNum(nowPriz);
			int step = ToolUtil.getFetchStep(nowPriz);
			tipInfo = "现抽取"+pname+"(共"+total+"名,分"+times+"次抽取,现第"+step+"次抽取"+fetchNum+"名)";
		}
		
		return tipInfo;
	}
	
	//刷新 显示，防止有字体滞留
	private void refreshView(){
		cardLayout.show(switchPanel, "resP");	
		cardLayout.show(switchPanel, "disP");
	}
	
	public void refreshViewForResultPanel(){
		cardLayout.show(switchPanel, "disP");
		cardLayout.show(switchPanel, "resP");			
	}
	
	public void stop_Action() {
		cardLayout.show(switchPanel, "disP");
		if(displayPanel.isRunning()){
			displayPanel.stop();
		}
		
		//停止时  提示当前抽的奖项 状态
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		
		int finishPrizeNum =0;
		for(Prize prize : prizes){
			if(prize.getIsFinish() || prize.getPersons().size()==prize.getTotal()){				
				finishPrizeNum++;
			}
		}
		if(finishPrizeNum==prizes.size()){
			//中间显示 所有的奖项 奖项已经抽完
			//displayPanel.showInTisPanel(" 所有的奖项已经抽完 ");
			//ShowInRunPanel("");
			
			butPn.changeReadyBtn(1);
			SystemUtil.setReadystatu(false);
			autoSave();
			return;
		}
		
		
		butPn.changeReadyBtn(1);			
		SystemUtil.setReadystatu(false);
		autoSave();
	}
	
	public void show_Action(){
		resPn.clearTable();
				
		List<String> reslist=SystemUtil.getResultPrizes();
		for(String pname:reslist){			
			resPn.showPrizesResult(SystemUtil.findPrizeByName(pname));
		}
		
		resPn.sugerTableFace();		
		cardLayout.show(switchPanel, "resP");
		resPn.startScroll();
	}
	
	public boolean getRunning(){
		return displayPanel.isRunning();
	}
	
	//打开基本设置
	public void open_Action() {
		if(baseSetFrame ==null){
			baseSetFrame = new BaseSetFrame();
			baseSetFrame.addObserver(this);				
		}
		baseSetFrame.showFrame();		
	}
	
	//改变背景图片
	public void change_Action(){
		String img=SystemUtil.backgroud_image;
		if(img==null||img.trim().isEmpty()){
			backImage = SystemUtil.createImageIcon("bg_red.jpg").getImage();
		}else{
			backImage = new ImageIcon(img).getImage();
		}
		this.repaint();
	}
	
	private void autoSave(){
		String path=SystemUtil.result_path;
		File file=null;
		if(path==null||path.trim().isEmpty()){
			file = new File("D:/result.txt");
			ExcelUtil.writeTXT(file);
		}else{
			try {
				file = new File(path);			
				if(SystemUtil.checkFileExtendName(file.getName(), "txt")){
					ExcelUtil.writeTXT(file);
				}else if(SystemUtil.checkFileExtendName(file.getName(), "xls")){				
					ExcelUtil.writeExcel(file);				
				}
			} catch (Exception e) {
				JOptionPane.showMessageDialog(null, "自动保存文件失败:"+e);
				e.printStackTrace();
				return;
			}
		}
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		Graphics2D g2=(Graphics2D)g;		
		g2.drawImage(backImage,0,0,null);
	}
}
